<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class User_management extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('flexigrid');
        $this->load->library('flexigrid');
        $this->load->library('form_validation');
        $this->load->model('user_man_model');
        $this->load->model('lisensi_model');
		$this->cek_login();
    }

	
	function cek_login(){
		$id_hak = $this->session->userdata('id_hak');
		if($id_hak < 1 || $id_hak > 3 || $id_hak == ''){
			redirect ('login');
		}
		
	}
	
	

    function index() {
        //ver lib

        /*
         * 0 - display name
         * 1 - width
         * 2 - sortable
         * 3 - align
         * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
         */
        $colModel['no'] = array('No', 40, TRUE, 'center', 0);
        $colModel['ubah'] = array('Edit', 50, FALSE, 'center', 0);
        $colModel['USERNAME'] = array('Username', 150, TRUE, 'center', 2);
        $colModel['PRIVILAGE'] = array('Privilage', 150, TRUE, 'center', 1);

        /*
         * Aditional Parameters
         */
        $gridParams = array(
            'width' => 'auto',
            'height' => '355',
            'rp' => 15,
            'rpOptions' => '[10,15,20,25,40]',
            'pagestat' => 'Displaying: {from} to {to} of {total} items.',
            'blockOpacity' => 0.5,
            'title' => 'Daftar Keseluruhan User'
        );

        /*
         * 0 - display name
         * 1 - bclass
         * 2 - onpress
         */
        $buttons[] = array('Tambah', 'add', 'user_man_js');
        $buttons[] = array('separator');
		$buttons[] = array('Hapus', 'delete', 'user_man_js');
        
        // $buttons[] = array('Select All', 'add', 'user_man_js');
        // $buttons[] = array('Deselect All', 'delete', 'user_man_js');
        // $buttons[] = array('separator');


        //Build js
        //View helpers/flexigrid_helper.php for more information about the params on this function
        $grid_js = build_grid_js('flex1', site_url("user/user_management/user_man_grid"), $colModel, 'no', 'asc', $gridParams, $buttons);

        $data['title'] = "Daftar Keseluruhan User";
        $data['info'] = "Data user";
        $data['js_grid'] = $grid_js;


        $data['added_js'] =
                "<script type='text/javascript'>
			function user_man_js(com,grid)
			{
				if (com=='Select All')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Deselect All')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Tambah')
				{
					location.href='" . base_url() . "index.php/user/user_management/input_user/'; 
				}
				
				if (com=='Hapus')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '" . site_url('user/user_management/delete_user') . "',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			} 
			</script>
			";



        //end if */	


        $this->template->write_view('header', 'template/header', $data);
        $this->template->write_view('content', 'user/grid_user', $data);
        $this->template->write_view('footer', 'template/footer', $data);
        $this->template->render();
    }

    function user_man_grid() {

        //List of all fields that can be sortable. This is Optional.
        //This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
        $valid_fields = array('ID_USER', 'USERNAME', 'PRIVILAGE');

        $this->flexigrid->validate_post('ID_USER', 'asc', $valid_fields);

        $records = $this->user_man_model->get_user_man_grid();

        $this->output->set_header($this->config->item('json_header'));
        $no = 1;
        /*
         * Json build WITH json_encode. If you do not have this function please read
         * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
         */
        foreach ($records['records']->result() as $row) {
            $record_items[] = array($row->ID_USER,
                $no,
                '<a href=\'' . base_url() . 'index.php/user/user_management/edit_user/' . $row->ID_USER . '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/edit.png\'></a> ',
                $row->USERNAME,
                $row->PRIVILAGE
            );
            $no++;
        }
        //Print please
        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }

    function cek_validasi() {
        // Setting Rule
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required|matches[repasswordbaru]');
		$this->form_validation->set_rules('repasswordbaru', 'Konfirmasi Password', 'required');
        $this->form_validation->set_rules('role', 'Role', 'callback_cek_dropdown');

        // Setting Error Message
        $this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
		$this->form_validation->set_message('matches', 'Password tidak sesuai.');

        // Setting Delimiter
        $this->form_validation->set_error_delimiters('<li class="error">', '</li>');
        return $this->form_validation->run();
    }

    function validasi_gantipassword() {
        $this->form_validation->set_rules('passwordlama', 'Password Lama', 'required|callback_cek_password_lama');
        $this->form_validation->set_rules('passwordbaru', 'Password Baru', 'required|matches[repasswordbaru]');
        $this->form_validation->set_rules('repasswordbaru', 'Konfirmasi Password', 'required');
        $this->form_validation->set_message('required', 'Kolom %s harus diisi.');
        $this->form_validation->set_message('matches', 'Password baru tidak sesuai.');

        $this->form_validation->set_error_delimiters('<li class="error">', '</li>');
        return $this->form_validation->run();
    }

    function input_user() {
        if ($this->cek_validasi() == FALSE) {
            $this->load->model('user_man_model');
            $data['status'] = 'new';
            $data['title'] = 'Tambah User';
            $data['roleoptions'] = $this->user_man_model->get_role();
            $data['lisensi'] = $this->lisensi_model->get_all_lisensi();
            $this->template->write_view('header', 'template/header', $data);
            $this->template->write_view('content', 'user/form_user_man', $data);
            $this->template->write_view('footer', 'template/footer', $data);
            $this->template->render();
        } else {
            $this->insert_user();
        }
    }

    function insert_user() {
        $data = array(
            'USERNAME' => $this->input->post('username'),
            'PASSWORD' => md5($this->input->post('password')),
            'STATUS' => 1,
            'ID_PRIVILAGE' => $this->input->post('role'),
            'ID_LISENSI' => $this->input->post('lisensi')
        );

        $this->user_man_model->insert_user($data);
        redirect('user/user_management');
    }

    function edit_user($id_user) {
        if ($this->cek_validasi() == FALSE) {

            $this->load->model('user_man_model');
			$data['title'] = 'Edit User';
            $data['status'] = 'edit';
            $data['user_man'] = $this->user_man_model->get_userID($id_user);
            $data['roleoptions'] = $this->user_man_model->get_role();
			$data['lisensi'] = $this->lisensi_model->get_all_lisensi();
            $this->template->write_view('header', 'template/header', $data);
            $this->template->write_view('content', 'user/form_user_man', $data);
            $this->template->write_view('footer', 'template/footer', $data);
            $this->template->render();
        } else {
            $this->update_user($id_user);
        }
    }

    function update_user($id_user) {
        $data = array(
            'USERNAME' => $this->input->post('username'),
            'PASSWORD' => md5($this->input->post('password')),
            'ID_PRIVILAGE' => $this->input->post('role')
        );

        $this->user_man_model->update_user($data, $id_user);
        redirect('user/user_management');
    }

    //Delete
    function delete_user() {
        $user_ids_post_array = explode(",", $this->input->post('items'));
        $msg = '';
        foreach ($user_ids_post_array as $index => $user_id) {
            if (isset($user_id) && $user_id != "") {
                $this->user_man_model->delete_user($user_id);


                $msg .= "User dengan id (" . $user_id . ") telah berhasil dihapus.\n";
            }
        }
        $this->output->set_header($this->config->item('ajax_header'));
        $this->output->set_output($msg);
    }

    function form_ganti_pass() {

        $data['status'] = 'new';
        $data['title'] = 'Ganti Password';

        $this->template->write_view('header', 'template/header', $data);
        $this->template->write_view('content', 'user/form_ganti_password', $data);
        $this->template->write_view('footer', 'template/footer', $data);
        $this->template->render();
    }
	
	
	function cek_password_lama($value){
		$users = $this->user_man_model->selectone($this->session->userdata('id_user'));
		foreach ($users->result() as $row) {
			if (md5($value) != $row->PASSWORD){
				$this->form_validation->set_message('cek_password_lama', 'Password lama salah.');
				return FALSE;
			}
			else{
				return TRUE;
			}
		}
	}
	
	
    function change_pass() {
        if ($this->validasi_gantipassword() == FALSE) {
            $this->form_ganti_pass();
        } else {
				$data = array(
					'PASSWORD' => md5($this->input->post('passwordbaru'))
				);
				$this->user_man_model->update_user($data, $this->session->userdata('id_user'));
				redirect('admin_home');
        }
    }

    function cek_dropdown($value) {
        if ($value === '0') {
            $this->form_validation->set_message('cek_dropdown', 'Kolom %s harus diisi!!');
            return FALSE;
        } else {
            return TRUE;
        }
    }

//end cek_dropdown
}

/* End of file user_management.php */
/* Location: ./application/controllers/user_management.php */
?>